import Vue from 'vue'
import VueRouter from 'vue-router'
// 一级路由
import Login from '@/views/login'
import Register from '@/views/register'
import Detail from '@/views/detail'
import Layout from '@/views/layout'
// 二级路由
import Like from '@/views/like'
import Article from '@/views/article'
import Collect from '@/views/collect'
import User from '@/views/user'
// 获取本地存储token
import { getToken } from '@/utils/storage'
// 全局导航守卫
Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    // 登入页
    { path: '/login', component: Login },
    // 注册页
    { path: '/register', component: Register },
    // 详情页
    { path: '/detail/:id', component: Detail },
    // 主页页
    { path: '/layout', redirect: '/article', component: Layout },
    // 主页
    {
      path: '/',
      component: Layout,
      redirect: '/article',
      children: [
        { path: '/article', component: Article },
        { path: '/like', component: Like },
        { path: '/collect', component: Collect },
        { path: '/user', component: User }
      ]
    }
  ]
})

// 白名单页面
const whiteList = ['/login', '/register']
router.beforeEach((to, from, next) => {
  // to 到那个页面去
  // from 从哪个页面来
  // 是否放行通过
  const token = getToken()
  if (token) {
    next()
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
})
export default router
